using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Ltf.Remoting.RemoteEvents;
using Microsoft.TeamFoundation.VersionControl.Client;
using Ltf.Remoting.TeamFoundation;
using ExtendedControls;

namespace Ltf.MonitorLizard.Forms
{
	[FormType(FormTypes.Properties)]
	public partial class TFProperties : Form
	{
		private VersionControlServer versionControlServer;

		public struct BranchInfo
		{
			public int Depth;
			public int FromId;
			public int ToId;

			public string FromName;
			public string ToName;
			public int FromChangesetId;
			public int ToChangesetId;

			public BranchInfo(int fromId, int toId,int depth)
			{
				this.Depth = depth;
				this.FromId = fromId;
				this.ToId = toId;
				this.FromName = string.Empty;
				this.ToName = string.Empty;
				this.FromChangesetId = 0;
				this.ToChangesetId = 0;
			}

			public void SetFromItem(Item item, VersionControlServer versionControlServer)
			{
				if (item != null)
				{
					int latest = versionControlServer.GetLatestChangesetId();
					FromName = versionControlServer.GetItem(item.ItemId, latest).ServerItem;
					FromChangesetId = item.ChangesetId;
				}
			}

			public void SetToItem(Item item, VersionControlServer versionControlServer)
			{
				if (item != null)
				{
					int latest = versionControlServer.GetLatestChangesetId();
					ToName = versionControlServer.GetItem(item.ItemId, latest).ServerItem;
					ToChangesetId = item.ChangesetId;
				}
			}

			public override string ToString()
			{
				return string.Format("{0}->{1} ({2}):{3};{4} -> {5};{6}", FromId, ToId, Depth, FromName, FromChangesetId, ToName, ToChangesetId);
			}
		}

		public TFProperties(string[] pathList, LizardEventArgs args)
		{
			InitializeComponent();
			lizardTFVCProps1.LoadFile(pathList[0]);
			versionControlServer = ServerConnections.GetConnectionForPath(pathList[0]).VersionControlServer;
			List<BranchInfo> bis = GetBranchInfo(pathList[0]);
			LoadBranchTree(pathList[0], bis);
		}

		public TFProperties()
		{
			InitializeComponent();
		}

		private void lizardTFVCProps1_Load(object sender, EventArgs e)
		{

		}

		private void LoadBranchTree(string path, List<BranchInfo> branches)
		{
			Workspace ws = ServerConnections.GetConnectionForPath(path).GetWorkspace(path);
			string serverPath = ws.GetServerItemForLocalItem(path);

			elvBranches.ViewMode = ExtendedListViewMode.Tree;
			elvBranches.BaseItems.Clear();
			Stack<ExtendedListViewItem> stack = new Stack<ExtendedListViewItem>();

			int curDepth = 0;
			ExtendedListViewItem lastItem = null;
			foreach (BranchInfo bi in branches)
			{
				ExtendedListViewItem ei = new ExtendedListViewItem(new string[] { bi.ToName, bi.FromChangesetId.ToString() });
				ei.ForeColor = (serverPath == bi.ToName) ? Color.Black : Color.DarkGray;
				ei.Depth = bi.Depth;
				ei.VirtualItem  = new ExtendedVirtualViewItem(elvBranches,ei);
				if (bi.Depth < curDepth)
					stack.Pop();
				else if (bi.Depth > curDepth)
					stack.Push(lastItem);

				if (stack.Count == 0)
				{
					elvBranches.BaseItems.Add(ei as ListViewItem);
				}
				else
				{
					elvBranches.BaseItems.Add(ei as ListViewItem);
					stack.Peek().Children.Add(ei);
					ei.ParentItem = stack.Peek().VirtualItem;
					ei.VirtualItem.ParentItem = ei.ParentItem;
					stack.Peek().VirtualItem.Children.Add(ei.VirtualItem);

				} curDepth = bi.Depth;
				lastItem = ei;

			}
			foreach (ExtendedListViewItem elvi in elvBranches.BaseItems)
				elvi.IsExpanded = true;

		}

		private List<BranchInfo> GetBranchInfo(string path)
		{
			VersionControlServer vcs = ServerConnections.GetConnectionForPath(path).VersionControlServer;
			VersionSpec versionSpec = VersionSpec.Latest;
			BranchHistoryTreeItem[] bhti = vcs.GetBranchHistory(new ItemSpec[] { new ItemSpec(path, RecursionType.None) }, versionSpec)[0];
			int postBranchChangeSet = 0;
			string matchPath = vcs.GetWorkspace(path).GetServerItemForLocalItem(path);
			List<BranchInfo> list = new List<BranchInfo>();
			nextId = 0;
			int count = nextId++;
			foreach (BranchInfo bi in EnumerateItems(bhti, count, 0))
				list.Add(bi);
			
			return list;
		}

		int nextId = 0;

		private IEnumerable<BranchInfo> EnumerateItems(IEnumerable<BranchHistoryTreeItem> items, int count, int depth)
		{
			foreach (BranchHistoryTreeItem ti in items)
			{
				int c = nextId++;
				BranchInfo bi = new BranchInfo(count, c, depth);
				bi.SetFromItem(ti.Relative.BranchFromItem, versionControlServer);
				bi.SetToItem(ti.Relative.BranchToItem, versionControlServer);
				yield return bi;
				List<BranchHistoryTreeItem> childItems = new List<BranchHistoryTreeItem>();
				foreach (object o in ti.Children)
					childItems.Add(o as BranchHistoryTreeItem);
				foreach (BranchInfo cbi in EnumerateItems(childItems,  c, depth + 1))
					yield return cbi;
			}
		}

		private void elvBranches_DoShowChildren(object sender, EventArgs e)
		{
			if (e is ExtendedListViewItemEventArgs)
			{
				//ExtendedListViewItem elvi = (e as ExtendedListViewItemEventArgs).ExtendedListViewItem;
				//int idx = elvi.Ordinal;
				//ExtendedVirtualViewItem vi = virtualItemCollection[idx];
				//HideChildren(vi, idx);
			}
		}

		private void elvBranches_DoHideChildren(object sender, EventArgs e)
		{
			if (e is ExtendedListViewItemEventArgs)
			{
				//ExtendedListViewItem elvi = (e as ExtendedListViewItemEventArgs).ExtendedListViewItem;
				//int idx = elvi.Ordinal;
				//ExtendedVirtualViewItem vi = virtualItemCollection[idx];
				//ShowChildren(vi, idx);
			}
		}
	}
}